import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { selectTextById, updateTextProperties } from '@/store/textsSlice';
import type { RootState } from '@/store';
import type { Text } from '@/store/textTypes';
import { Form, Input, InputNumber, Switch, Select, Typography, Row, Col, Tabs, Slider } from 'antd';
import { createGlobalStyle } from 'styled-components';

const { Title, Text } = Typography;
const { Option } = Select;

// 颜色转换辅助函数
// 将十六进制颜色转换为0-1范围的RGB数组
const hexToRgb = (hex: string): [number, number, number] => {
    if (!hex.startsWith('#')) return [0, 0, 0];
    const r = parseInt(hex.slice(1, 3), 16) / 255;
    const g = parseInt(hex.slice(3, 5), 16) / 255;
    const b = parseInt(hex.slice(5, 7), 16) / 255;
    return [r, g, b];
};
// 将0-1范围的RGB数组转换为十六进制颜色字符串
const rgbToHex = (rgb: number[]): string => {
    return `#${rgb
        .map((c) => {
            const hex = Math.round(c * 255).toString(16);
            return hex.length === 1 ? '0' + hex : hex;
        })
        .join('')}`;
};

// 全局 Ant Design 深色主题样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* ... (样式代码与之前组件相同，此处为简洁省略) ... */
    .config-text-form-scroll::-webkit-scrollbar { width: 3px; background: transparent; }
    .config-text-form-scroll::-webkit-scrollbar-thumb { background: #715BB8; border-radius: 4px; }
    .ant-form-item-label > label { color: #FFFFFF !important; }
    .ant-input, .ant-input-number, .ant-select-selector {
        background-color: #3C3C3C !important; color: #FFFFFF !important; border-color: #555555 !important;
    }
    .ant-input:hover, .ant-input:focus, .ant-input-number:hover, .ant-input-number:focus,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important; box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-input-number-handler-wrap { background-color: #3C3C3C !important; }
    .ant-input-number-handler { color: #FFFFFF !important; border-color: #555555 !important; }
    .ant-select-dropdown { background-color: #3C3C3C !important; }
    .ant-select-item-option { color: #FFFFFF !important; }
    .ant-select-item-option-selected { background-color: #555555 !important; }
    .ant-select-arrow { color: #FFFFFF !important; }
    .ant-switch { background-color: #555555 !important; }
    .ant-switch-checked { background-color: #715BB8 !important; }
    .ant-tabs-nav { margin-bottom: 24px !important; }
    .ant-tabs-tab { color: #AAAAAA !important; }
    .ant-tabs-tab:hover { color: #FFFFFF !important; }
    .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn { color: #715BB8 !important; }
    .ant-tabs-ink-bar { background: #715BB8 !important; }
    /* 自定义颜色选择器样式 */
    .ant-input[type="color"] {
        padding: 2px !important; /* 减小内边距，让颜色块更大 */
        height: 32px;
    }
    /* 滑块 (Slider) 样式 */
    .ant-slider-rail {
        background-color: #555555 !important;
    }
    .ant-slider-track {
        background-color: #FFFFFF !important;
    }
    .ant-slider-handle {
        border: solid 2px #FFFFFF !important;
        background-color: #3C3C3C !important;
    }
    .ant-slider-handle:focus {
        box-shadow: 0 0 0 5px rgba(255, 255, 255, 0.12) !important;
    }
`;

interface FormValues {
    content: string;
    font: string;
    timerange_start: number;
    timerange_duration: number;
    style: {
        size: number;
        bold: boolean;
        italic: boolean;
        underline: boolean;
        color: string;
        alpha: number;
        align: number;
        vertical: boolean;
        letter_spacing: number;
        line_spacing: number;
    };
    border: { alpha: number; color: string; width: number };
    background: {
        color: string;
        style: number;
        alpha: number;
        round_radius: number;
        height: number;
        width: number;
        horizontal_offset: number;
        vertical_offset: number;
    };
}
interface ConfigTextFormProps {
    textId: string;
}

// 辅助组件：用于创建标签-滑块-数值输入的组合行
const SliderInputRow: React.FC<{
    label: string;
    name: string[];
    sliderProps: any;
    inputProps: any;
}> = ({ label, name, sliderProps, inputProps }) => (
    <Form.Item>
        <Row align="middle" gutter={16}>
            <Col span={6}>
                <Text style={{ color: '#FFFFFF' }}>{label}</Text>
            </Col>
            <Col span={12}>
                <Form.Item name={name} noStyle>
                    <Slider {...sliderProps} />
                </Form.Item>
            </Col>
            <Col span={6}>
                <Form.Item name={name} noStyle>
                    <InputNumber style={{ width: '90%' }} {...inputProps} />
                </Form.Item>
            </Col>
        </Row>
    </Form.Item>
);

const ConfigTextForm: React.FC<ConfigTextFormProps> = ({ textId }) => {
    const [form] = Form.useForm();
    const dispatch = useDispatch();
    const text = useSelector((state: RootState) => (textId ? selectTextById(state, textId) : null));
    const trackItem = useSelector((state: RootState) => (textId ? state.tracks.tracks.flatMap((track) => track.items).find((item) => item.type === 'text' && item.id === textId) : null));

    const handleFormChange = React.useCallback(
        (allValues: FormValues) => {
            if (!textId) return;

            // 确保style、border和background对象存在，但保留已有的颜色值
            const safeStyle = allValues.style || {};
            const safeBorder = allValues.border || {};
            const safeBackground = allValues.background || {};

            const updates: Partial<Text> = {
                content: allValues.content,
                font: allValues.font,
                timerange: [allValues.timerange_start, allValues.timerange_duration],
                style: {
                    ...safeStyle,
                    // 只有在color存在时才更新，避免将颜色重置为黑色
                    ...(safeStyle.color ? { color: hexToRgb(safeStyle.color) } : {}),
                },
                border: {
                    ...safeBorder,
                    // 只有在color存在时才更新，避免将颜色重置为黑色
                    ...(safeBorder.color ? { color: hexToRgb(safeBorder.color) } : {}),
                },
                background: {
                    ...safeBackground,
                    // 只有在color存在时才更新，避免将颜色重置为白色
                    ...(safeBackground.color ? { color: safeBackground.color } : {}),
                },
            };
            dispatch(updateTextProperties({ id: textId, updates }));
        },
        [textId, dispatch]
    );

    useEffect(() => {
        if (text) {
            const formValues: FormValues = {
                content: text.content,
                font: text.font,
                timerange_start: text.timerange[0],
                timerange_duration: text.timerange[1],
                style: { ...text.style, color: rgbToHex(text.style.color) },
                border: { ...text.border, color: rgbToHex(text.border.color) },
                background: {
                    ...text.background,
                    color: text.background.color,
                }, // 直接使用十六进制颜色字符串
            };
            form.setFieldsValue(formValues);
        }
    }, [text, form]);

    if (!textId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何文本片段
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            <div
                className="config-text-form-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前选择
                </Title>
                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '24px',
                        border: '1px solid #555555',
                    }}
                >
                    <Text style={{ color: '#FFFFFF' }}>
                        <i className="icon-text">T</i> {text?.content.substring(0, 20) || '未命名文本'}...
                    </Text>
                </div>

                <Form form={form} layout="vertical" onValuesChange={handleFormChange}>
                    <Title level={5} style={{ color: '#FFFFFF', marginTop: 0 }}>
                        基础信息
                    </Title>
                    <Form.Item name="content" label="文本内容" rules={[{ required: true }]}>
                        <Input.TextArea value={text?.content || ''} onChange={(e) => form.setFieldValue('content', e.target.value)} placeholder="请输入文本内容" rows={4} style={{ minHeight: '80px' }} />
                    </Form.Item>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="开始时间(s)" name="timerange_start">
                                <InputNumber min={0} step={0.1} precision={2} style={{ width: '90%' }} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="持续时间(s)" name="timerange_duration">
                                <InputNumber min={0.1} step={0.1} precision={2} style={{ width: '90%' }} />
                            </Form.Item>
                        </Col>
                    </Row>

                    {/* **改动: 使用 Tabs 对设置项进行分类** */}
                    <Tabs
                        defaultActiveKey="style"
                        items={[
                            {
                                key: 'style',
                                label: '字体样式',
                                children: (
                                    <>
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Form.Item label="字号" name={['style', 'size']}>
                                                    <InputNumber min={1} max={200} style={{ width: '80%' }} />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="颜色" name={['style', 'color']}>
                                                    <Input type="color" style={{ width: '80%' }} />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <Row gutter={16}>
                                            <Col span={8}>
                                                <Form.Item label="加粗" name={['style', 'bold']} valuePropName="checked">
                                                    <Switch />
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label="下划线" name={['style', 'underline']} valuePropName="checked">
                                                    <Switch />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <SliderInputRow
                                            label="透明度"
                                            name={['style', 'alpha']}
                                            sliderProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                            inputProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                        />
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Form.Item label="字符间距" name={['style', 'letter_spacing']}>
                                                    <InputNumber min={0} max={100} style={{ width: '80%' }} />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="行间距" name={['style', 'line_spacing']}>
                                                    <InputNumber min={0} max={100} style={{ width: '80%' }} />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </>
                                ),
                            },
                            {
                                key: 'border',
                                label: '描边',
                                children: (
                                    <>
                                        <Row gutter={16}>
                                            <Col span={8}>
                                                <Form.Item label="宽度" name={['border', 'width']}>
                                                    <InputNumber min={0} max={100} style={{ width: '80%' }} />
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label="颜色" name={['border', 'color']}>
                                                    <Input type="color" style={{ width: '80%' }} />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <SliderInputRow
                                            label="透明度"
                                            name={['border', 'alpha']}
                                            sliderProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                            inputProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                        />
                                    </>
                                ),
                            },
                            {
                                key: 'background',
                                label: '背景',
                                children: (
                                    <>
                                        <Row gutter={16}>
                                            <Col span={8}>
                                                <Form.Item label="颜色" name={['background', 'color']}>
                                                    <Input
                                                        type="color"
                                                        style={{
                                                            width: '100%',
                                                        }}
                                                    />
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label="样式" name={['background', 'style']}>
                                                    <Select style={{ width: '80%' }}>
                                                        <Option value={1}>样式1</Option>
                                                        <Option value={2}>样式2</Option>
                                                    </Select>
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <SliderInputRow
                                            label="透明度"
                                            name={['background', 'alpha']}
                                            sliderProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                            inputProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                        />
                                        <SliderInputRow
                                            label="圆角半径"
                                            name={['background', 'round_radius']}
                                            sliderProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                            inputProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                        />
                                        <SliderInputRow
                                            label="宽度"
                                            name={['background', 'width']}
                                            sliderProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                            inputProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                        />
                                        <SliderInputRow
                                            label="高度"
                                            name={['background', 'height']}
                                            sliderProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                            inputProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                        />
                                        <SliderInputRow
                                            label="水平偏移"
                                            name={['background', 'horizontal_offset']}
                                            sliderProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                            inputProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                        />
                                        <SliderInputRow
                                            label="垂直偏移"
                                            name={['background', 'vertical_offset']}
                                            sliderProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                            inputProps={{
                                                min: 0,
                                                max: 1,
                                                step: 0.1,
                                            }}
                                        />
                                    </>
                                ),
                            },
                        ]}
                    />
                </Form>
            </div>
        </>
    );
};

export default ConfigTextForm;
